package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.entity.views.ResStudentGrade;
import com.xmy.cultivate.entity.views.ShiftList;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusGradeEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.ResStudentGradeData;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.Result;
import com.xmy.cultivate.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 学生所在班级与课程 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-09
 */
@Service
@Slf4j
public class StudentGradeServiceImpl extends ServiceImpl<StudentGradeMapper, StudentGrade> implements IStudentGradeService {

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    IStudentLessonNumService iStudentLessonNumService;

    @Autowired
    @Lazy
    CourseSchedulingAlwaysMapper courseSchedulingAlwaysMapper;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Lazy
    ICourseSchedulingAlwaysService iCourseSchedulingAlwaysService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    @Lazy
    ICisPositionService iCisPositionService;

    @Autowired
    @Lazy
    ICompanyService iCompanyService;

    @Autowired
    @Lazy
    IStudentGradeAddTypeService iStudentGradeAddTypeService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    @Lazy
    IFeiEnglishFeignClient iFeiEnglishFeignClient;

    @Autowired
    @Lazy
    IStudentNewsService iStudentNewsService;

    @Autowired
    IStudentGradeContinueService iStudentGradeContinueService;

    public IPage<ShiftList> findAll(IPage<?> page, Wrapper wrapper) {
        return studentGradeMapper.findAll(page, wrapper);
    }

    public Result divideClasses(Long orderDetailId, Long gradeId) {

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if (orderDetail == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        } else if (orderDetail.getResidueCourseCount() <= 0) {
            throw new CommonException(ResultCode.NOR_COURSE);
        }

        Grade grade = gradeMapper.selectById(gradeId);
        if (grade == null) {
            throw new CommonException(ResultCode.GRADE_NOT);
        } else if (grade.getStatus() != StatusGradeEnum.NORMAL) {
            throw new CommonException(ResultCode.KNOTGRADE);
        }

        Long studentId = orderDetail.getStudentId();
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

        if (grade.getLessonType().equals(1)) {
            studentGradeQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
            studentGradeQueryWrapper.eq("lesson_type", grade.getLessonType());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("year_part", orderDetail.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 4);//在读和停课
            studentGradeQueryWrapper.last("limit 1");
            StudentGrade studentGradeAt = studentGradeMapper.selectOne(studentGradeQueryWrapper);
            if (studentGradeAt != null) {
                //return new Result(Code.ERROR, "", "该科目存在停课，不能分班，先把该科目复课再分班");
            }

            studentGradeQueryWrapper.clear();

            studentGradeQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
            studentGradeQueryWrapper.eq("lesson_type", grade.getLessonType());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("year_part", orderDetail.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);//在读和停课
            studentGradeQueryWrapper.last("limit 1");
            StudentGrade studentGradeAtForSubjects = studentGradeMapper.selectOne(studentGradeQueryWrapper);

            if (studentGradeAtForSubjects != null) {
                if (!studentGradeAtForSubjects.getGradeId().equals(gradeId)) {
                    //return new Result(Code.ERROR, "", "不能同时分在不同的班级，分班失败");
                }
            }

            studentGradeQueryWrapper.clear();
            //studentGradeQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
            //studentGradeQueryWrapper.eq("year_part",orderDetail.getYearPart());
            //studentGradeQueryWrapper.eq("quarter_num",orderDetail.getQuarterNum());
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);//在读和停课
            studentGradeQueryWrapper.last("limit 1");
            studentGradeAt = studentGradeMapper.selectOne(studentGradeQueryWrapper);
            if (studentGradeAt != null) {
                return new Result(Code.ERROR, "", "订单已经存在分班，不要重复分班");
            }
        }


        StudentGrade studentGrade = new StudentGrade();
        studentGrade.setOrderDetailId(orderDetail.getId());
        studentGrade.setStudentId(studentId);
        studentGrade.setSchoolId(orderDetail.getSchoolId());
        studentGrade.setGradeId(grade.getId());
        studentGrade.setCourseId(orderDetail.getCourseId());
        studentGrade.setSubjectsId(orderDetail.getSubjectsId());
        studentGrade.setEndDate(grade.getEndDate());
        studentGrade.setLessonType(grade.getLessonType());
        studentGrade.setClassTypeIdNew(grade.getCourseTypeId());

        //studentGrade.setUseCourseCount();
        /*Long renewTeacherId = grade.getTeacherId();
        Integer isRenew = 1;
        //课次
        if((orderDetail.getResidueCourseCount()/orderDetail.getCourseHouse())<3){
            isRenew = 0;
            //应续班老师,为原来的带班老师，待设定
        }else {
            //应续班老师
            studentGrade.setRenewTeacherId(renewTeacherId);
        }*/
        Course course = courseMapper.selectById(grade.getCourseId());
        studentGrade.setYearClassId(course.getYearClassId().getKey());

        studentGrade.setYearPart(orderDetail.getYearPart());
        studentGrade.setQuarterNum(orderDetail.getQuarterNum());
        studentGrade.setSurplusCourseNum(orderDetail.getResidueCourseCount());
        //studentGrade.setIsRenew(isRenew);
        Integer rs = studentGradeMapper.insert(studentGrade);

        //更新续班里的老师
        iRenewDataService.updateTeacher(grade.getSchoolId(), studentId, course, grade);
        //更新为最后一条
        this.updateIsLast(grade.getYearPart(), course.getQuarterNum(), studentId, orderDetail.getSubjectsId(), grade.getLessonType());
        //同步帐号信息到其它系统
        //if (course.getSubjectsId().equals(1L)){
        //iStudentAccountService.applyAddStudentAccount(orderDetail.getSchoolId(), studentId, grade.getId(), orderDetail.getCourseId());
        //}
        //同步帐号信息到其它系统
        iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId());


        //添加缺课数据
        if (course.getLessonType().equals(1)) {
            iLackCourseLogService.batchAdd(grade.getYearPart(), course.getQuarterNum(), grade.getSchoolId(), studentId, course.getSubjectsId(), course.getYearClassId().getKey(), gradeId, 1, 1);
        }

        //添加学生课次
        iStudentLessonNumService.addStudentLesson(grade.getId(), studentId);

        if (grade.getLessonType().equals(1)) {
            try {
                iMqPushService.updateIsPresort(orderDetail.getSchoolId(), studentId, orderDetail.getYearPart(), course.getQuarterNum(), course.getSubjectsId(), course.getLessonType());
                //智能课、刷题班分班
                StudentGrade studentGradeAllot = new StudentGrade();
                studentGradeAllot.setYearPart(grade.getYearPart());
                studentGradeAllot.setQuarterNum(grade.getQuarterNum());
                studentGradeAllot.setSchoolId(grade.getSchoolId());
                studentGradeAllot.setGradeId(grade.getId());
                studentGradeAllot.setStudentId(studentId);
                studentGradeAllot.setSubjectsId(course.getSubjectsId());
                studentGradeAllot.setLessonType(grade.getLessonType());
                iMqPushService.autoAllotStudentGrade(studentGradeAllot);
            } catch (Exception e) {
            }
        }


        Result result = new Result(rs > 0 ? Code.OK : Code.ERROR, "", "");
        return result;
    }

    /**
     * 调班
     *
     * @param paramStudentGrade
     * @return
     */
    @Override
    @Transactional
    public Result melodyClass(StudentGrade paramStudentGrade) {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer yearPartAndQuarterNow = Integer.parseInt(quarterNow.getYearPart() + "" + quarterNow.getNum());

        Long outGradeId = paramStudentGrade.getOutGradeId();
        Long inGradeId = paramStudentGrade.getInGradeId();
        String[] studentIdList = paramStudentGrade.getStudentIdList();

        Grade grade = gradeMapper.selectById(inGradeId);

        Grade outGrade = gradeMapper.selectById(outGradeId);
        if (outGrade.getStatus().equals(2)) {
            throw new CommonException(ResultCode.GRADE_IS_FINISH);
        }

        Course course = courseMapper.selectById(grade.getCourseId());
        Integer yearPartAndQuarter = Integer.parseInt(grade.getYearPart() + "" + course.getQuarterNum());

        List<String> stringList = new ArrayList<>();
        String clashStr = "";

        LocalDateTime nowDateTime = LocalDateTime.now();
        for (String studentId : studentIdList) {
            List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClash(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), grade.getId(), nowDateTime.toString());
            if (repairCourseList.size() > 0) {
                Student student = studentMapper.selectById(Long.parseLong(studentId));
                for (RepairCourse repairCourse : repairCourseList) {
                    //不等于转出校区的
                    if (repairCourse.getGradeId() != null) {
                        if (!repairCourse.getGradeId().equals(outGradeId)) {
                            clashStr = student.getName() + "," + repairCourse.getGradeName() + "" + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                            stringList.add(clashStr);
                        }
                    } else {
                        String courseTypeName = CommonUtil.getCourseTypeName(repairCourse.getCourseType());
                        clashStr = student.getName() + "," + courseTypeName + repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + " " + repairCourse.getTimeEnd();
                        stringList.add(clashStr);
                    }
                }
            }

            Integer isAtGrade = studentGradeMapper.studentIsAtGrade(Long.parseLong(studentId), grade.getId());
            if (isAtGrade > 0) {
                Student student = studentMapper.selectById(Long.parseLong(studentId));
                clashStr = student.getName() + "：已存在在读或者停课信息，调班失败";
                stringList.add(clashStr);
            }
        }
        if (stringList.size() > 0) {
            StringBuilder studentBuilder = new StringBuilder();
            studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
            return new Result(Code.ERROR, stringList, studentBuilder.toString());
        }


        // 判断调出和调入是否为同一个老师
        try {
            if (!outGrade.getTeacherId().equals(grade.getTeacherId())) {
                outGrade.setStudentIdList(studentIdList);
                outGrade.setInSchoolId(grade.getSchoolId());
                outGrade.setInTeacherId(grade.getTeacherId());
                // 同步mq离职或调班学员信息
                iMqPushService.leaveTeacherStudent(outGrade);
            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        for (String studentId : studentIdList) {
            String studentStat = this.studentAtGradeState(outGradeId, Long.parseLong(studentId), 2);
            if (!studentStat.equals("1") && !studentStat.equals("0")) {
                continue;
            }
            //剩余课时
            Integer courseHouse = orderDetailMapper.getResidueCourseCountForSubjects(grade.getSchoolId(), Long.parseLong(studentId), course.getSubjectsId(), yearPartAndQuarterNow, grade.getLessonType());
            OrderDetail orderDetail = orderDetailMapper.getLastOneForSubjectId(grade.getSchoolId(), Long.parseLong(studentId), course.getSubjectsId(), quarterNow.getYearPart(), quarterNow.getNum(), course.getLessonType());
            if (orderDetail == null) {
                continue;
            }

            Integer isAtGrade = studentGradeMapper.studentIsAtGrade(Long.parseLong(studentId), grade.getId());
            //System.out.print("isAtGrade:" + isAtGrade);
            if (isAtGrade == 0) {
                //是否有预分班数据
                StudentGrade studentGradePresort = studentGradeMapper.getPresortData(Long.parseLong(studentId), outGradeId);
                StudentGrade studentGrade = new StudentGrade();
                if (studentGradePresort != null) {
                    studentGrade.setIsPresort(studentGradePresort.getIsPresort());
                    studentGrade.setReadingStatus(studentGradePresort.getReadingStatus());
                    //studentGrade.setCreatedAt(studentGradePresort.getCreatedAt());
                }

                studentGrade.setSchoolId(grade.getSchoolId());
                studentGrade.setGradeId(grade.getId());
                studentGrade.setCourseId(grade.getCourseId());
                studentGrade.setSubjectsId(course.getSubjectsId());
                studentGrade.setYearClassId(course.getYearClassId().getKey());
                studentGrade.setYearPart(grade.getYearPart());
                studentGrade.setQuarterNum(course.getQuarterNum());
                studentGrade.setSurplusCourseNum(courseHouse);
                studentGrade.setStudentId(Long.parseLong(studentId));

                StudentGrade studentGradeBefor = studentGradeMapper.getStudentGradeForGradeId(Long.parseLong(studentId), outGradeId);
                if (!Objects.isNull(studentGradeBefor)) {
                    studentGrade.setClassTypeIdNew(studentGradeBefor.getClassTypeIdNew());
                } else {
                    studentGrade.setClassTypeIdNew(grade.getCourseTypeId());
                }

                if (orderDetail != null) {
                    studentGrade.setOrderDetailId(orderDetail.getId());
                }
                //System.out.print("添加成功:" + isAtGrade);
                //studentGradeMapper.insert(studentGrade);
                this.save(studentGrade);
                //更新为之前的预分班时间
                if (studentGradePresort != null) {
                    studentGrade.setCreatedAt(studentGradePresort.getCreatedAt());
                    this.updateById(studentGrade);
                }
                Integer yearAndQuarter = Integer.parseInt(grade.getYearPart() + "" + course.getQuarterNum());

                if (outGrade.getTeacherId() != grade.getTeacherId()) {
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("student_id", studentId).eq("grade_id", outGradeId).eq("status", 1).eq("deleted", 0).eq("reading_status", 1);
                    List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
                    if (studentGradeList.size() == 1) {
                        for (StudentGrade studentGrade1 : studentGradeList) {
                            if (studentGrade1.getUseCourseCount() == 0) {
                                iRenewDataService.updateTeacher(studentGrade1.getSchoolId(), Long.parseLong(studentId), course, grade);
                            } else {
                                /**
                                 * 剩余课次
                                 */
                                Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentGrade1.getSchoolId(), Long.parseLong(studentId), course.getSubjectsId(), yearAndQuarter, course.getLessonType());
                                if (residueCourseCount >= 7) {
                                    iRenewDataService.updateTeacher(studentGrade1.getSchoolId(), Long.parseLong(studentId), course, grade);
                                }
                            }
                        }
                    } else {
                        for (StudentGrade studentGrade1 : studentGradeList) {
                            if (studentGrade1.getUseCourseCount() == 0) {
                                iRenewDataService.updateTeacher(studentGrade1.getSchoolId(), Long.parseLong(studentId), course, grade);
                            } else {
                                /**
                                 * 剩余课次
                                 */
                                Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentGrade1.getSchoolId(), Long.parseLong(studentId), course.getSubjectsId(), yearAndQuarter, course.getLessonType());
                                if (residueCourseCount >= 7) {
                                    iRenewDataService.updateTeacher(studentGrade1.getSchoolId(), Long.parseLong(studentId), course, grade);
                                }
                            }
                        }
                    }
                }

                UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                //设置为转出
                studentGradeUpdateWrapper.eq("student_id", studentId).eq("grade_id", outGradeId).eq("status", 1).set("status", 2).set("reading_status", 2);
                studentGradeMapper.update(null, studentGradeUpdateWrapper);
                if (studentGradePresort != null) {
                    if (studentGradePresort.getUseCourseCount() == 0) {
                        //预分班的使用为0的删除
                        studentGradeMapper.deleteById(studentGradePresort);
                    }
                }

                //更新为最后一条
                this.updateIsLast(grade.getYearPart(), course.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), grade.getLessonType());
                if (grade.getLessonType().equals(1)) {
                    //添加缺课数据
                    iLackCourseLogService.batchAdd(grade.getYearPart(), course.getQuarterNum(), grade.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), course.getYearClassId().getKey(), grade.getId(), 1, 1);
                }
                //添加学生课次
                iStudentLessonNumService.addStudentLesson(grade.getId(), Long.parseLong(studentId));
                //添加智能课帐号
                /*if (course.getSubjectsId().equals(1L)){
                    iStudentAccountService.applyAddStudentAccount(orderDetail.getSchoolId(), Long.parseLong(studentId), grade.getId(), orderDetail.getCourseId());
                }*/
            }

            // 判断是否与student_class_type表班型一致
            QueryWrapper<StudentClassType> studentClassTypeQueryWrapper = new QueryWrapper<>();
            studentClassTypeQueryWrapper.eq("student_id", studentId);
            studentClassTypeQueryWrapper.eq("subjects_id", grade.getSubjectsId());
            studentClassTypeQueryWrapper.eq("year_class_id", grade.getYearClassId());
            studentClassTypeQueryWrapper.eq("year_part", grade.getYearPart());
            studentClassTypeQueryWrapper.eq("quarter_num", grade.getQuarterNum());
            studentClassTypeQueryWrapper.orderByDesc("id");
            studentClassTypeQueryWrapper.last("limit 1");
            StudentClassType studentClassType = iStudentClassTypeService.getOne(studentClassTypeQueryWrapper);
            if (studentClassType != null) {
                if (studentClassType.getClassTypeId().equals(grade.getCourseTypeId())) {
                    studentClassType.setIsAdjust(1);
                    studentClassType.setAdjustDateTime(LocalDateTime.now());
                } else {
                    if (paramStudentGrade.getAdminId().equals(1568138350324350975L)) {
                        // 管理员操作，如果班型不一致，则更改is_fit为0
                        studentClassType.setIsFit(0);
                    }
                    studentClassType.setIsAdjust(0);
                }
                iStudentClassTypeService.updateById(studentClassType);
            }
        }

        return new Result(Code.OK, "", "成功");
    }

    @Override
    public Long addData(Long orderDetailId, Long schoolId, Long studentId, Long gradeId, Long courseId, Long subjectsId, Integer yearPart, Integer quarterNum, Integer surplusCourseNum, Integer yearClassId, Integer lessonType, Long classTypeIdNew, Integer lackType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("school_id", schoolId);
        studentGradeQueryWrapper.eq("reading_status", 4);//如果有停课
        Long count = this.count(studentGradeQueryWrapper);
        ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
        if (count > 0) {
            readingStatusEnum = ReadingStatusEnum.STOP;
        }

        studentGradeQueryWrapper.clear();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("school_id", schoolId);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.eq("is_last", 1);
        studentGradeQueryWrapper.eq("reading_status", 1);
        studentGradeQueryWrapper.last("limit 1");
        StudentGrade studentGradeAt = this.getOne(studentGradeQueryWrapper);
        LocalDateTime localDateTimeNow = LocalDateTime.now().withNano(0);
        StudentGrade studentGrade = new StudentGrade();

        if (studentGradeAt != null) {
            //因为到课率计算会用到这个时间，因为如存在有数据，就使用有数据的时间
            localDateTimeNow = studentGradeAt.getCreatedAt();
            studentGrade.setClassTypeIdNew(studentGradeAt.getClassTypeIdNew());
        } else {
            studentGrade.setClassTypeIdNew(classTypeIdNew);
        }
        studentGrade.setOrderDetailId(orderDetailId);
        studentGrade.setYearClassId(yearClassId);
        studentGrade.setSchoolId(schoolId);
        studentGrade.setStudentId(studentId);
        studentGrade.setGradeId(gradeId);
        studentGrade.setCourseId(courseId);
        studentGrade.setSubjectsId(subjectsId);
        studentGrade.setYearPart(yearPart);
        studentGrade.setQuarterNum(quarterNum);
        studentGrade.setSurplusCourseNum(surplusCourseNum);
        studentGrade.setLessonType(lessonType);
        studentGrade.setReadingStatus(readingStatusEnum);
        studentGrade.setCreatedAt(localDateTimeNow);
        studentGradeMapper.insert(studentGrade);
        if (studentGradeAt != null) {
            studentGrade.setCreatedAt(studentGradeAt.getCreatedAt());
            studentGradeMapper.updateById(studentGrade);
        }
        //0为新生
        /*Long applyCount = iOrderApplyService.getApplyCount(subjectsId.toString(),studentId.toString());
        if (applyCount.equals(0L)){
            StudentGradeAddType studentGradeAddType = new StudentGradeAddType();
            studentGradeAddType.setStudentGradeId(studentGrade.getId());
            studentGradeAddType.setType(2);
            Grade newGrade = this.getNewGrade(yearPart,quarterNum,schoolId,subjectsId,yearClassId,studentId,lessonType);
            Integer addType =1;
            if (newGrade != null) {
                if (gradeId.equals(newGrade.getId())) {
                    addType = 2;
                }
            }
            studentGradeAddType.setAddType(addType);
            iStudentGradeAddTypeService.addData(studentGradeAddType);
        }*/

        //更新为最后一条
        //this.updateIsLast(yearPart, quarterNum, studentId, subjectsId, lessonType);
        iMqPushService.updateStudentGradeLast(yearPart, quarterNum, studentId, subjectsId, lessonType);

        //添加缺课数据
        //iLackCourseLogService.batchAdd(yearPart, quarterNum, schoolId, studentId, subjectsId, yearClassId, gradeId, 1);
        iMqPushService.lackCourseLogBatchAdd(yearPart, quarterNum, schoolId, studentId, subjectsId, yearClassId, gradeId, 1, lackType);
        //添加学生课次
        //iStudentLessonNumService.addStudentLesson(gradeId, studentId);
        iMqPushService.addStudentLesson(gradeId, studentId);
        //添加智能课帐号
        /*if (subjectsId.equals(1L)){
            iStudentAccountService.applyAddStudentAccount(schoolId, studentId, gradeId, courseId);
        }*/
        //同步帐号信息到其它系统
        iMqPushService.updateStudentAccount(yearPart, quarterNum, studentId, subjectsId);
        return studentGrade.getId();
    }

    /**
     * 不存在就添加
     *
     * @param orderDetailId
     * @param schoolId
     * @param studentId
     * @param courseId
     * @param subjectsId
     * @param yearPart
     * @param quarterNum
     * @param surplusCourseNum
     * @return
     */
    @Override
    public boolean notDataAndAddData(Long orderDetailId, Long schoolId, Long studentId, Long courseId, Long subjectsId, Integer yearPart, Integer quarterNum, Integer surplusCourseNum, Integer yearClassId, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("school_id", schoolId);
        studentGradeQueryWrapper.eq("course_id", courseId);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.eq("status", 1);
        studentGradeQueryWrapper.eq("reading_status", 1);
        studentGradeQueryWrapper.last("limit 1");
        StudentGrade studentGradeInfo = studentGradeMapper.selectOne(studentGradeQueryWrapper);
        if (studentGradeInfo != null) {
            Grade grade = iGradeService.getById(studentGradeInfo.getGradeId());
            StudentGrade studentGrade = new StudentGrade();
            studentGrade.setOrderDetailId(orderDetailId);
            studentGrade.setSchoolId(studentGradeInfo.getSchoolId());
            studentGrade.setStudentId(studentId);
            studentGrade.setGradeId(studentGradeInfo.getGradeId());
            studentGrade.setCourseId(courseId);
            studentGrade.setSubjectsId(subjectsId);
            studentGrade.setYearClassId(yearClassId);
            studentGrade.setYearPart(yearPart);
            studentGrade.setQuarterNum(quarterNum);
            studentGrade.setSurplusCourseNum(surplusCourseNum);
            studentGrade.setLessonType(lessonType);
            studentGrade.setClassTypeIdNew(studentGradeInfo.getClassTypeIdNew());
            /*if (grade!=null){
                studentGrade.setClassTypeIdNew(grade.getCourseTypeId());
            }*/

            studentGradeMapper.insert(studentGrade);
            studentGrade.setCreatedAt(studentGradeInfo.getCreatedAt());
            studentGradeMapper.updateById(studentGrade);

            //添加缺课数据
            iLackCourseLogService.batchAdd(yearPart, quarterNum, schoolId, studentId, subjectsId, yearClassId, studentGradeInfo.getGradeId(), 1, 1);
            //添加学生课次
            iStudentLessonNumService.addStudentLesson(studentGradeInfo.getGradeId(), studentId);
        } else {
            /*studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", yearPart);
            studentGradeQueryWrapper.eq("quarter_num", quarterNum);
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("school_id", schoolId);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("course_id", courseId);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("lesson_type", lessonType);
            studentGradeQueryWrapper.in("reading_status", 3, 5);//不包含停课的，排停课的排除4,
            studentGradeQueryWrapper.orderByDesc("reading_status");
            studentGradeQueryWrapper.last("limit 1");
            studentGradeInfo = studentGradeMapper.selectOne(studentGradeQueryWrapper);
            if (studentGradeInfo != null) {
                Grade grade = iGradeService.getById(studentGradeInfo.getGradeId());
                StudentGrade studentGrade = new StudentGrade();
                studentGrade.setOrderDetailId(orderDetailId);
                studentGrade.setSchoolId(studentGradeInfo.getSchoolId());
                studentGrade.setStudentId(studentId);
                studentGrade.setGradeId(studentGradeInfo.getGradeId());
                studentGrade.setCourseId(courseId);
                studentGrade.setSubjectsId(subjectsId);
                studentGrade.setYearClassId(yearClassId);
                studentGrade.setYearPart(yearPart);
                studentGrade.setQuarterNum(quarterNum);
                studentGrade.setSurplusCourseNum(surplusCourseNum);
                studentGrade.setLessonType(lessonType);
                if (grade!=null){
                    studentGrade.setClassTypeIdNew(grade.getCourseTypeId());
                }
                studentGradeMapper.insert(studentGrade);
                //添加缺课数据
                iLackCourseLogService.batchAdd(yearPart, quarterNum, schoolId, studentId, subjectsId, yearClassId, studentGradeInfo.getGradeId(), 1);
                //添加学生课次
                iStudentLessonNumService.addStudentLesson(studentGradeInfo.getGradeId(), studentId);
            }*/
        }
        this.updateIsLast(yearPart, quarterNum, studentId, subjectsId, lessonType);
        /*if (studentGradeInfo != null) {
            //添加智能课帐号
            if (subjectsId.equals(1L)){
                iStudentAccountService.applyAddStudentAccount(schoolId, studentId, studentGradeInfo.getGradeId(), courseId);
            }
        }*/
        //同步帐号信息到其它系统
        iMqPushService.updateStudentAccount(yearPart, quarterNum, studentId, subjectsId);
        return true;
    }


    /**
     * 学生在班级的状态
     *
     * @return
     */
    public String studentAtGradeState(Long gradeId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = "";
        if (studentGrade != null) {
            if (reType == null || reType == 1) {
                /*if (studentGrade.getStatus().equals(4)){
                    state = "转校"+studentGrade.getReadingStatus().getValue();
                }else {
                    state = studentGrade.getReadingStatus().getValue();
                }*/
                state = studentGrade.getReadingStatus().getValue();
            } else if (reType == 2) {
                state = studentGrade.getReadingStatus().getKey().toString();
            }
        }
        return state;
    }

    /**
     * 学生在班级的课时状态
     *
     * @return
     */
    public String getCourseStatus(Long gradeId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = studentGrade.getCourseStatus().toString();
        return state;
    }


    /**
     * 学生在班级的状态
     *
     * @return
     */
    public String studentAtGradeStateForOrderDetailId(Long orderDetailId, Long studentId, Integer reType) {
        Student student = studentMapper.selectById(studentId);
        OrderDetail orderDetail = iOrderDetailService.getById(orderDetailId);

        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", orderDetailId);
        studentGradeQueryWrapperForStudent.eq("lesson_type", orderDetail.getLessonType());
        studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.orderByDesc("id");
        studentGradeQueryWrapperForStudent.last("limit 1");
        StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);
        String state = "";
        if (studentGrade != null) {
            if (reType == null || reType == 1) {
                state = studentGrade.getReadingStatus().getValue();
            } else if (reType == 2) {
                state = studentGrade.getReadingStatus().getKey().toString();
            }
        }
        return state;
    }

    /**
     * 结课
     *
     * @param studentGrade
     * @return
     */
    public boolean finishCourse(StudentGrade studentGrade) {

        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                Course course = courseMapper.selectById(gradeInfo.getCourseId());
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 1);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.FINISH);
                    studentGradeMapper.updateById(studentGradeItem);
                }
                if (course.getSubjectsId().equals(1L)) {
                    //更新智能课班型
                    iStudentAccountService.updateClassType(gradeInfo.getYearPart(), gradeInfo.getQuarterNum(), course.getSubjectsId(), studentGrade.getStudentId());
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }


    /**
     * 固定
     *
     * @return
     */
    @Override
    public boolean studentFixed(StudentGrade studentGrade) {
        UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("student_id", studentGrade.getStudentId());
        updateWrapper.eq("grade_id", studentGrade.getGradeId());
        updateWrapper.ne("status", 3);
        updateWrapper.eq("add_type", 2);
        updateWrapper.set("scheduling_type", 1);
        this.update(updateWrapper);
        return true;
    }

    @Override
    public boolean studentFixedCancel(StudentGrade studentGrade) {
        UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("student_id", studentGrade.getStudentId());
        updateWrapper.eq("grade_id", studentGrade.getGradeId());
        updateWrapper.ne("status", 3);
        updateWrapper.eq("add_type", 2);
        updateWrapper.set("scheduling_type", 0);
        this.update(updateWrapper);
        return true;
    }

    /**
     * 停课
     *
     * @param studentGrade
     * @return
     */
    @Override
    public boolean stopGrade(StudentGrade studentGrade) {
        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            //不等于结课
            if (!gradeInfo.getStatus().equals(StatusGradeEnum.DISABLE)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 1);

                QueryWrapper<StudentGrade> studentGradeQueryWrapper = studentGradeQueryWrapperForStudent.clone();

                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());

                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.STOP);
                    studentGradeItem.setStopCourseDate(LocalDate.now());
                    studentGradeMapper.updateById(studentGradeItem);
                }
                Long readingCount = studentGradeMapper.selectCount(studentGradeQueryWrapper);
                if (readingCount.equals(0L)) {
                    //如果不存在在读学生，班级改为停课
                    gradeInfo.setStatus(StatusGradeEnum.STOP);
                    iGradeService.updateById(gradeInfo);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    /**
     * 根据班级停课
     *
     * @param gradeId
     * @return
     */
    @Override
    @Transactional
    public boolean stopGradeId(String gradeId) {
        Grade gradeInfo = gradeMapper.selectById(gradeId);
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(new QueryWrapper<StudentGrade>().eq("grade_id", gradeId));

        if (gradeInfo != null) {
            if (!gradeInfo.getStatus().equals(StatusGradeEnum.DISABLE)) {
                gradeInfo.setStatus(StatusGradeEnum.STOP);
                iGradeService.updateById(gradeInfo);
                for (StudentGrade studentGrade : studentGradeList) {
                    QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                    studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                    studentGradeQueryWrapperForStudent.eq("deleted", 0);
                    studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                    studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
                    studentGradeQueryWrapperForStudent.ne("status", 3);
                    studentGradeQueryWrapperForStudent.eq("reading_status", 1);
                    List<StudentGrade> studentGradeList1 = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                    for (StudentGrade studentGradeItem : studentGradeList1) {
                        studentGradeItem.setReadingStatus(ReadingStatusEnum.STOP);
                        studentGradeItem.setStopCourseDate(LocalDate.now());
                        studentGradeMapper.updateById(studentGradeItem);
                    }
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }

    }


    /**
     * 复课
     *
     * @param studentGrade
     * @return
     */
    @Override
    public boolean agrainGrade(StudentGrade studentGrade) {
        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("reading_status", 4);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.IN_READING);
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    @Override
    public boolean courseStatusChange(StudentGrade studentGrade) {

        String courseStatus = this.getCourseStatus(studentGrade.getGradeId(), studentGrade.getStudentId(), 1);

        Grade gradeInfo = gradeMapper.selectById(studentGrade.getGradeId());
        Long studentId = studentGrade.getStudentId();
        Long gradeId = studentGrade.getGradeId();

        if (gradeInfo != null) {
            if (gradeInfo.getStatus().getKey().equals(1)) {
                Student student = studentMapper.selectById(studentId);
                QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted", 0);
                studentGradeQueryWrapperForStudent.eq("grade_id", gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id", student.getId());
                studentGradeQueryWrapperForStudent.ne("status", 3);
                studentGradeQueryWrapperForStudent.eq("course_status", courseStatus);
                //studentGradeQueryWrapperForStudent.last("limit 1");
                List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
                if (courseStatus.equals("1")) {
                    courseStatus = "0";
                } else {
                    courseStatus = "1";
                }
                for (StudentGrade studentGradeItem : studentGradeList) {
                    studentGradeItem.setCourseStatus(Integer.parseInt(courseStatus));
                    studentGradeMapper.updateById(studentGradeItem);
                }
                return true;
            } else {
                return false;
            }
        } else {
            throw new CommonException(ResultCode.NOTDATA);
        }
    }

    @Override
    public boolean finishCourseForOrder(StudentGrade studentGrade) {

        //OrderDetail orderDetail = orderDetailMapper.selectById(studentGrade.getOrderDetailId());
        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("order_detail_id", studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 1);
        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (gradeInfo.getStatus().getKey().equals(1)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.FINISH);
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
            }
        }
        return rs;
    }

    @Override
    public boolean stopGradeForOrder(StudentGrade studentGrade) {
        OrderDetail orderDetail = iOrderDetailService.getById(studentGrade.getOrderDetailId());

        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);
        studentGradeQueryWrapperForStudent.eq("year_part", orderDetail.getYearPart());
        studentGradeQueryWrapperForStudent.eq("quarter_num", orderDetail.getQuarterNum());
        studentGradeQueryWrapperForStudent.eq("subjects_id", orderDetail.getSubjectsId());
        studentGradeQueryWrapperForStudent.eq("lesson_type", orderDetail.getLessonType());
        //studentGradeQueryWrapperForStudent.eq("order_detail_id",studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 1);
        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (gradeInfo.getStatus().getKey().equals(1)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.STOP);
                    studentGradeItem.setStopCourseDate(LocalDate.now());
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
            }
        }
        return rs;
    }

    @Override
    public boolean agrainGradeForOrder(StudentGrade studentGrade) {

        QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
        studentGradeQueryWrapperForStudent.orderByDesc("created_at");
        studentGradeQueryWrapperForStudent.eq("deleted", 0);

        Integer lessonType = 1;
        if (studentGrade.getOrderDetailId() != null) {
            OrderDetail orderDetail = iOrderDetailService.getById(studentGrade.getOrderDetailId());
            lessonType = orderDetail.getLessonType();
            studentGradeQueryWrapperForStudent.eq("year_part", orderDetail.getYearPart());
            studentGradeQueryWrapperForStudent.eq("quarter_num", orderDetail.getQuarterNum());
            studentGradeQueryWrapperForStudent.eq("subjects_id", orderDetail.getSubjectsId());
        } else {
            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            studentGradeQueryWrapperForStudent.eq("year_part", grade.getYearPart());
            studentGradeQueryWrapperForStudent.eq("quarter_num", grade.getQuarterNum());
            Course course = iCourseService.getById(grade.getCourseId());
            studentGradeQueryWrapperForStudent.eq("subjects_id", course.getSubjectsId());
        }

        studentGradeQueryWrapperForStudent.eq("lesson_type", lessonType);
        //studentGradeQueryWrapperForStudent.eq(studentGrade.getOrderDetailId() != null,"order_detail_id", studentGrade.getOrderDetailId());
        studentGradeQueryWrapperForStudent.ne("status", 3);
        studentGradeQueryWrapperForStudent.eq("reading_status", 4);
        studentGradeQueryWrapperForStudent.eq("student_id", studentGrade.getStudentId());


        //studentGradeQueryWrapperForStudent.last("limit 1");
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapperForStudent);
        boolean rs = false;
        for (StudentGrade studentGradeItem : studentGradeList) {
            Grade gradeInfo = gradeMapper.selectById(studentGradeItem.getGradeId());
            if (gradeInfo != null) {
                if (!gradeInfo.getStatus().equals(StatusGradeEnum.DISABLE)) {
                    studentGradeItem.setReadingStatus(ReadingStatusEnum.IN_READING);
                    studentGradeMapper.updateById(studentGradeItem);
                    rs = true;
                }
                if (gradeInfo.getStatus().equals(StatusGradeEnum.STOP)) {
                    gradeInfo.setStatus(StatusGradeEnum.NORMAL);
                    iGradeService.updateById(gradeInfo);
                }
                //班级如果停课，改为正常
                if (gradeInfo.getStatus().equals(StatusGradeEnum.STOP)) {
                    gradeInfo.setStatus(StatusGradeEnum.NORMAL);
                    iGradeService.updateById(gradeInfo);
                }
            }
        }
        return rs;
    }

    @Override
    public boolean agrainBatchGradeForOrder(StudentGrade studentGrade) {
        for (String studentId : studentGrade.getStudentIdList()) {
            StudentGrade studentGradeInfo = new StudentGrade();
            studentGradeInfo.setGradeId(studentGrade.getGradeId());
            studentGradeInfo.setStudentId(Long.parseLong(studentId));
            this.agrainGradeForOrder(studentGradeInfo);

            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            Course course = iCourseService.getById(grade.getCourseId());
            iMqPushService.updateStudentAccount(grade.getYearPart(), grade.getQuarterNum(), Long.parseLong(studentId), course.getSubjectsId());

            // 判断是否在新生表
            QueryWrapper<StudentNews> studentNewsQueryWrapper = new QueryWrapper<>();
            studentNewsQueryWrapper.eq("student_id", studentId);
            studentNewsQueryWrapper.eq("year_part", grade.getYearPart());
            studentNewsQueryWrapper.eq("quarter_num", grade.getQuarterNum());
            studentNewsQueryWrapper.eq("subjects_id", grade.getSubjectsId());
            studentNewsQueryWrapper.last("limit 1");
            StudentNews studentNews = iStudentNewsService.getOne(studentNewsQueryWrapper);
            if (studentNews != null) {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(grade.getYearPart(), grade.getQuarterNum());
                if (quarter.getType() == 1) {
//                    if (studentNews.getIsAddLack() == 1) {
                    // 添加所有的缺课
                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), Long.valueOf(studentId), 6, null, 2);
//                    } else {
//                        // 添加created_at时间之后的排课缺课
//                        LocalDateTime createdAt = studentNews.getCreatedAt();
//                        iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), Long.valueOf(studentId), 6, String.valueOf(createdAt));
//                    }
                } else {
                    // 假期班，添加所有的缺课
                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), Long.valueOf(studentId), 6, null, 2);
                }
            } else {
                if (grade.getLessonType().equals(1)) {
                    // 复课后缺课
                    iCourseSchedulingDetailService.resumeClassesLackCourse(grade.getId(), Long.valueOf(studentId), 6, null, 2);
                }
            }

        }
        return true;
    }

    public List<StudentGrade> getlist(Long gradeId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_id", gradeId);
        List<StudentGrade> gradeList = studentGradeMapper.getStudentGradeList(queryWrapper);
        return gradeList;
    }

    /**
     * 获取班级在读人数
     */
    public Integer getGradeStudyCount(Long gradeId) {
        QueryWrapper<StudentGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_id", gradeId);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("reading_status", 1);
        queryWrapper.eq("deleted", 0);
        Long count = studentGradeMapper.selectCount(queryWrapper);
        return Integer.valueOf(count.toString());
    }

    public Integer getStudentGradeUseCount(Long schoolId, Long studentId, Long subjectsId) {
        Integer count = studentGradeMapper.getStudentGradeUseCount(schoolId, studentId, subjectsId);
        return count;
    }

    public Long getStudentCount(@Param(Constants.WRAPPER) QueryWrapper queryWrapper) {
        return studentGradeMapper.getStudentCount(queryWrapper);
    }

    /**
     * 获取最后一次后班数据
     *
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @param yearPart
     * @param quaterNum
     * @return
     */
    public StudentGrade getLastStudentGradeForOrderDetailId(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, Integer lessonType) {
        StudentGrade studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 1, lessonType);
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 5, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 6, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 4, lessonType);
        }
        if (studentGrade == null) {
            studentGrade = this.getStudentGradeForOrderDetailIdOne(schoolId, studentId, subjectsId, yearPart, quaterNum, 2, lessonType);
        }
        return studentGrade;
    }

    public Long getStudentGradeCount(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId) {
        return studentGradeMapper.getStudentGradeCount(yearPart, quarterNum, schoolId, subjectsId, studentId);
    }


    public StudentGrade getStudentGradeForOrderDetailIdOne(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quaterNum, Integer readingStatus, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quaterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq(schoolId != null, "school_id", schoolId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("reading_status", readingStatus);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        //studentGradeQueryWrapper.eq("reading_status",1);
        studentGradeQueryWrapper.last("limit 1");
        studentGradeQueryWrapper.orderByDesc("id", "created_at");
        StudentGrade studentGrade = this.getOne(studentGradeQueryWrapper);
        return studentGrade;
    }

    public Long getStudentUseCourseCount(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getStudentUseCourseCount(yearPart, quarterNum, schoolId, subjectsId, studentId, lessonType);
    }

    @Override
    public Long getStudentUseCourseCountAllSchool(Integer yearPart,
                                                  Integer quarterNum,
                                                  Long subjectsId,
                                                  Long studentId,
                                                  Integer lessonType) {
        return studentGradeMapper.getStudentUseCourseCountAllSchool(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    /**
     * 是否使用满15次课，不分校区
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @param lessonType
     * @return
     */
    public Long getStudentUseCourseCountForRecourse(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getStudentUseCourseCountForRecourse(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }

    public List<StudentGrade> getGroupByAtNewList(QueryWrapper queryWrapper) {
        return studentGradeMapper.getGroupByAtNewList(queryWrapper);
    }

    /**
     * 更新最后一条数据
     *
     * @return
     */
    @Override
    public boolean updateIsLast(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer lessonType) {
        try {
            QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
            studentGradeQueryWrapperNew.eq("year_part", yearPart);
            studentGradeQueryWrapperNew.eq("quarter_num", quarterNum);
            studentGradeQueryWrapperNew.eq("student_id", studentId);
            studentGradeQueryWrapperNew.ne("status", 3);
            //studentGradeQueryWrapperNew.ne("year_class_id", yearClassId);
            studentGradeQueryWrapperNew.eq("subjects_id", subjectsId);
            studentGradeQueryWrapperNew.eq("lesson_type", lessonType);
            studentGradeQueryWrapperNew.orderByDesc("id");
            List<StudentGrade> studentGradeListNew = this.list(studentGradeQueryWrapperNew);
            Integer i = 0;
            for (StudentGrade studentGradeNew : studentGradeListNew) {
                if (i == 0) {
                    studentGradeNew.setIsLast(1);
                } else {
                    studentGradeNew.setIsLast(0);
                }
                this.updateById(studentGradeNew);
                i++;
            }
            studentGradeQueryWrapperNew.clear();
            return true;
        } catch (Exception e) {

        }
        return true;
    }

    /**
     * 在读学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer inReadStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String yearClassId = (String) reMap.get("yearClassId");
        String teacherId = (String) reMap.get("teacherId");
        String status = (String) reMap.get("status");


        Integer inReadStudentCount = studentGradeMapper.readingStudentCount(yearPart, quarterNum, schoolId, subjectsId, lessonType, yearClassId, teacherId, status, null, null, null);
        return inReadStudentCount;
    }

    /**
     * 异常学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer abnormalStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer errorStudentCount = studentGradeMapper.abnormalStudentCount(yearPart, quarterNum, schoolId, subjectsId, lessonType);
        return errorStudentCount;
    }

    /**
     * 结课学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer overStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        Integer overStudentCount = studentGradeMapper.countStudentByStatusJoint(yearPart, quarterNum, schoolId, subjectsId, lessonType);
        return overStudentCount;
    }

    /**
     * 退费学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer returnStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer returnStudentCount = studentGradeMapper.returnStudentCount(yearPart, quarterNum, schoolId, subjectsId, lessonType);

        return returnStudentCount;
    }

    /**
     * 转校学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer changeStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer changeStudentCount = studentGradeMapper.turnOutStudentCount(yearPart, quarterNum, schoolId, subjectsId, lessonType);
        return changeStudentCount;
    }

    /**
     * 停课学员数量
     *
     * @param reMap
     * @return
     */
    @Override
    public Integer stopStudentCount(Map reMap, String lessonType) {
        String schoolId = (String) reMap.get("schoolId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");

        Integer stopStudentCount = studentGradeMapper.stopStudnetCount(yearPart, quarterNum, schoolId, subjectsId, lessonType);
        return stopStudentCount;
    }

    /**
     * 批量核对
     *
     * @param gradeId
     * @param studentId
     * @return
     */
    @Override
    public Integer updateIsCheckHouse(String gradeId, String studentId) {
        return studentGradeMapper.updateIsCheckHouse(gradeId, studentId);
    }

    /**
     * 核对人数统计
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param yearClassId
     * @param courseId
     * @return
     */
    @Override
    public Long getStudentCheckCount(String yearPart, String quarterNum, String schoolId, String subjectsId, String yearClassId, String courseId, String teacherId, String isCheckHouse, String lessonType, Integer sourseLeve, Long adminId) {
        return studentGradeMapper.getStudentCheckCount(yearPart, quarterNum, schoolId, subjectsId, yearClassId, courseId, teacherId, isCheckHouse, lessonType, sourseLeve, adminId);
    }


    /**
     * 学生课时是否核对
     *
     * @return
     */
    public Long isCheckHouse(Long gradeId, Long studentId) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("is_check_house", 0);
        studentGradeQueryWrapper.eq("grade_id", gradeId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.ne("status", 3);
        Long count = this.count(studentGradeQueryWrapper);
        return count;
    }

    public List<ResStudentGradeData> getStudentScheduling(Integer yearPart, Integer quarterNum, String weekDates, String timeStart, String timeEnd, String studentStr, String lessonType) {
        return studentGradeMapper.getStudentScheduling(yearPart, quarterNum, weekDates, timeStart, timeEnd, studentStr, lessonType);
    }

    @Override
    public StudentGrade getStudentForLast(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.orderByDesc("id");
        studentGradeQueryWrapper.last("limit 1");
        StudentGrade studentGrade = this.getOne(studentGradeQueryWrapper);
        return studentGrade;
    }

    @Override
    public StudentGrade getLastForMaxId(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getLastForMaxId(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }


    @Override
    @Async("onlineAsync")
    public void batchUpdateStudentAccount(Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.eq("is_last", 1);
        studentGradeQueryWrapper.orderByDesc("id");
        List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            iStudentAccountService.updateClassTypeForStudentGrade(studentGrade);
        }
    }


    /**
     * 修改预分班的状态
     *
     * @param schoolId
     * @param studentId
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param lessonType
     */
    @Override
    public void updateIsPresort(Long schoolId, Long studentId, Integer yearPart, Integer quarterNum, Long subjectsId, Integer lessonType) {
        Integer yearPartAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer residueCount = orderDetailMapper.getResidueCourseCount(schoolId, studentId, subjectsId, yearPartAndQuarter, lessonType);
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);

        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        //为了获取年级信息
        OrderDetail lastOrderDetail = orderDetailMapper.getLastOneForStudent(yearPart, quarterNum, studentId, subjectsId, lessonType);

        Integer gradeSection = CommonUtil.getGradeSection(lastOrderDetail.getYearClassId());
        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getOneForDate(LocalDate.now(), gradeSection);
        if (courseSchedulingAlways != null) {
            if (courseSchedulingAlways.getNum() <= 3) {
                nextYearPart = yearPart;
                nextQuarterNum = quarterNum;
            }

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part", nextYearPart);
            studentGradeQueryWrapper.eq("quarter_num", nextQuarterNum);
            studentGradeQueryWrapper.eq("subjects_id", subjectsId);
            studentGradeQueryWrapper.eq("student_id", studentId);
            if (residueCount < 15) {
                studentGradeQueryWrapper.eq("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(4);
                    studentGrade.setRemark("课时小于15，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                    iStudentGradeContinueService.changeFail(studentGrade,4);//设置为失败
                }
            } else {
                studentGradeQueryWrapper.ne("is_presort", 1);
                List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    studentGrade.setIsPresort(1);
                    iStudentGradeContinueService.addData(studentGrade,1);//添加到预分班
                    studentGrade.setRemark("课时大于15，" + "时间：" + LocalDateTime.now().withNano(0));
                    this.updateById(studentGrade);
                }
            }
        }
    }

    @Override
    public List<Grade> getGrade(Wrapper wrapper) {
        return studentGradeMapper.getGrade(wrapper);
    }

    @Override
    @Async
    public void updateOrderDetailId(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, Long subjectsId, Long orderDetailId) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("school_id", schoolId);
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.isNull("order_detail_id");
        List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            studentGrade.setOrderDetailId(orderDetailId);
            studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
            this.updateById(studentGrade);
        }
    }


    @Override
    @Async
    public void updateStudentIsPresort() {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Integer yearPart = quarterNow.getYearPart();
        Integer quarterNum = quarterNow.getNum();
        LocalDate localDate = LocalDate.now();

        CourseSchedulingAlways courseSchedulingAlwaysFive = courseSchedulingAlwaysMapper.getOneForNum(yearPart, quarterNum, 5);

        CourseSchedulingAlways courseSchedulingAlwaysTen = courseSchedulingAlwaysMapper.getOneForNum(yearPart, quarterNum, 10);

        //第5次课之前的计算当前学期
        if (courseSchedulingAlwaysFive != null && courseSchedulingAlwaysFive.getEndDate().isAfter(localDate)) {
            //log.error("进入当前学期");
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("year_part", yearPart);
            recordCourseQueryWrapper.eq("quarter", quarterNum);
            recordCourseQueryWrapper.eq("school_date", localDate);
            recordCourseQueryWrapper.eq("lesson_type", 1);
            recordCourseQueryWrapper.eq("is_deduct_house", 1);
            recordCourseQueryWrapper.eq("status", 1);
            List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
            //log.error("recordCourseList:" + recordCourseList.size());
            for (RecordCourse recordCourse : recordCourseList) {
                try {
                    if (recordCourse.getLessonNum() != null && recordCourse.getLessonNum() <= 3) {
                        Integer allCourseCount = orderDetailMapper.getAllCourseCountForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearAndQuarter(), 1);
                        if (allCourseCount >= 3) {
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("year_part", yearPart);
                            studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                            studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                            studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                            studentGradeQueryWrapper.eq("lesson_type", 1);
                            studentGradeQueryWrapper.eq("status", 1);
                            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGradeList) {
                                if (studentGrade.getIsPresort().equals(1)) {
                                    studentGrade.setIsPresort(2);//预分班续报成功
                                    iStudentGradeContinueService.addData(studentGrade,2);//添加到预分班
                                    this.updateById(studentGrade);
                                } else {
                                    studentGrade.setIsPresort(3);//没有添加预分班的，续报成功
                                    iStudentGradeContinueService.addData(studentGrade,3);//添加到预分班
                                    this.updateById(studentGrade);
                                }
                            }
                        } else {
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("year_part", yearPart);
                            studentGradeQueryWrapper.eq("quarter_num", quarterNum);
                            studentGradeQueryWrapper.eq("student_id", recordCourse.getStudentId());
                            studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                            studentGradeQueryWrapper.eq("lesson_type", 1);
                            studentGradeQueryWrapper.eq("status", 1);
                            studentGradeQueryWrapper.eq("is_presort", 1);
                            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGradeList) {
                                studentGrade.setRemark("小与3次课，续报失败");
                                studentGrade.setIsPresort(4);
                                iStudentGradeContinueService.changeFail(studentGrade,4);//设置为失败
                                this.updateById(studentGrade);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }

        }

        //第10次课之后的计算下一个学期
        if (courseSchedulingAlwaysTen != null && courseSchedulingAlwaysTen.getEndDate().isBefore(localDate)) {
            //log.error("进入下一学期");
            Quarter quarterNext = CommonUtil.getNextQuarter(yearPart, quarterNum);
            Integer yearAndQuarter = Integer.parseInt(quarterNow.getYearPart() + "" + quarterNow.getNum());
            //获取预分班学生信息
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("is_presort", 1);
            studentGradeQueryWrapper.eq("year_part", quarterNext.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num", quarterNext.getNum());
            List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);
            for (StudentGrade studentGrade : studentGradeList) {
                try {
                    //剩余课次
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentGrade.getSchoolId(), studentGrade.getStudentId(), studentGrade.getSubjectsId(), yearAndQuarter, 1);
                    if (residueCourseCount > 0 && residueCourseCount < 3) {
                        /**Integer count = studentGradeMapper.getIsPresortCount(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getSchoolId(),studentGrade.getSubjectsId(),studentGrade.getStudentId());
                         if (count>0){

                         }*/
                        studentGrade.setIsPresort(4);
                        studentGrade.setRemark("低于3次课，续报失败");
                        iStudentGradeContinueService.changeFail(studentGrade,4);//设置为失败
                        this.updateById(studentGrade);
                    } else if (residueCourseCount.equals(0)) {
                        studentGrade.setIsPresort(4);
                        iStudentGradeContinueService.changeFail(studentGrade,4);//设置为失败
                        studentGrade.setRemark("剩余0次课，续报失败");
                        this.updateById(studentGrade);

                        if (studentGrade.getUseCourseCount().equals(0)) {
                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                            studentGradeUpdateWrapper.eq("id", studentGrade.getId());
                            studentGradeUpdateWrapper.set("deleted", 1);
                            this.update(studentGradeUpdateWrapper);
                        }
                        //this.removeById(studentGrade.getId());
                    }
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    @Async
    public void newQuarterUpdateClassType(Integer yearPart, Integer quarterNum, Integer readingStatus, Integer subjectsId) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", yearPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.eq("lesson_type", 1);
        studentGradeQueryWrapper.eq("status", 1);
        studentGradeQueryWrapper.eq("reading_status", readingStatus);
        //studentGradeQueryWrapper.eq("student_id", 1644542053108940800L);
        studentGradeQueryWrapper.groupBy("student_id");
        List<StudentGrade> studentGradeList = this.list(studentGradeQueryWrapper);

        Integer i = 0;
        for (StudentGrade studentGrade : studentGradeList) {
            try {
                iMqPushService.updateStudentAccount(yearPart, quarterNum, studentGrade.getStudentId(), studentGrade.getSubjectsId());

                /*Grade grade = gradeMapper.selectById(studentGrade.getGradeId());
                ResStudentClassType studentClassType = new ResStudentClassType();

                studentClassType.setClassTypeId(grade.getCourseTypeId());
                studentClassType.setStudentId(studentGrade.getStudentId());
                studentClassType.setSchoolId(studentGrade.getSchoolId());
                studentClassType.setYearClassId(grade.getYearClassId().getKey());
                studentClassType.setGradeId(studentGrade.getGradeId());
                studentClassType.setQuarterNum(studentGrade.getQuarterNum());
                studentClassType.setYearPart(studentGrade.getYearPart());
                studentClassType.setTeacherId(grade.getTeacherId());
                studentClassType.setGradeSection(CommonUtil.getGradeSection(grade.getYearClassId().getKey()));
                iFeiEnglishFeignClient.newQuarterUpdateClassType(studentClassType);//使用iFeiEnglish*/

                //以下改为了使用mq
                //ResStudentAccount resStudentAccount = new ResStudentAccount();
                //BeanUtils.copyProperties(studentClassType, resStudentAccount);
                //resStudentAccount.setSubjectsId(studentGrade.getSubjectsId());
                //rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_STUDENT_ACCOUNT_FANOUT,null,resStudentAccount);

            } catch (Exception e) {
                //log.error(e.getMessage());
            }
            //log.info("studentCount:" + studentGradeList.size() + "i:" + i);
        }
    }

    @Override
    public Grade getClassTypeNameForStudentId(Integer yearPart,
                                              Integer quarterNum,
                                              Long studentId,
                                              Long subjectsId) {
        Grade grade = null;

        if (subjectsId == null) {
            //return classTypeName;
            return null;
        }
        try {
            grade = studentGradeMapper.getClassTypeNameForStudentId(yearPart, quarterNum, studentId, subjectsId);
        } catch (Exception e) {
        }
        return grade;
    }

    /**
     * 获取班型
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @param lessonType
     * @return
     */
    @Override
    public ResStudentGrade getStudentGradeClassType(Integer yearPart,
                                                    Integer quarterNum,
                                                    Long subjectsId,
                                                    Long studentId,
                                                    Integer lessonType) {
        return studentGradeMapper.getStudentGradeClassType(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }


    @Override
    public IPage<StudentGrade> getStudentGradeLastList(IPage<?> page, Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId) {
        return studentGradeMapper.getStudentGradeLastList(page, yearPart, quarterNum, schoolId, subjectsId, studentId);
    }

    /**
     * 获取最后一条分班信息
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @param lessonType
     * @return
     */
    @Override
    public StudentGrade getLastOne(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer lessonType) {
        return studentGradeMapper.getLastOne(yearPart, quarterNum, subjectsId, studentId, lessonType);
    }


    @Override
    @Async("onlineAsync")
    public void studentClassGradePushMq(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart != null && quarterNum != null) {
            quarterNow.setYearPart(yearPart);
            quarterNow.setNum(quarterNum);
        }

        Integer pageSize = 100;
        IPage<StudentGrade> iPage = new Page<>(1, pageSize);
        this.getStudentGradeLastList(iPage, quarterNow.getYearPart(), quarterNow.getNum(), schoolId, subjectsId, studentId);

        Long allPage = iPage.getPages();
        for (Integer i = 1; i <= allPage; i++) {
            iPage = new Page<>(i, pageSize);
            this.getStudentGradeLastList(iPage, quarterNow.getYearPart(), quarterNow.getNum(), schoolId, subjectsId, studentId);
            for (StudentGrade studentGrade : iPage.getRecords()) {
                StudentClassType studentClassType = new StudentClassType();
                BeanUtils.copyProperties(studentGrade, studentClassType);
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                if (grade != null) {
                    studentClassType.setGradeId(grade.getId());
                    studentClassType.setGradeSection(grade.getYearClassId().getKey());
                    studentClassType.setTeacherId(grade.getTeacherId());
                    studentClassType.setSchoolId(grade.getSchoolId());
                    Staff staff = iStaffService.getById(grade.getTeacherId());
                    if (staff != null) {
                        studentClassType.setTeacherName(staff.getName());
                    }
                }
                //iMqPushService.updateStudentClassType(studentClassType);
                iMqPushService.updateStudentAccount(quarterNow.getYearPart(), quarterNow.getNum(), studentGrade.getStudentId(), studentGrade.getSubjectsId());

            }
        }
    }

    @Override
    public Boolean updateClassTypeByGradeId(Long classTypeId, Long gradeId) {
        return studentGradeMapper.updateClassTypeByGradeId(classTypeId, gradeId);
    }

    /**
     * 新生报名自动添加
     *
     * @param orderDetailId
     * @param schoolId
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param subjectsId
     * @param yearClassId
     * @param courseId
     * @param surplusCourseNum
     * @param lessonType
     * @return
     */
    @Override
    public boolean addNewStudentGrade(Long orderDetailId, Long schoolId, Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer yearClassId, Long courseId, Integer surplusCourseNum, Integer lessonType) {
        try {
            Company company = iCompanyService.getById(CommonConstant.companyId);
            if (company == null) {
                return false;
            }
            if (company.getStuIsHierarchy().equals(1)) {
                //0为新生
                Long count = iOrderApplyService.getApplyCountForIsNew(subjectsId.toString(), studentId.toString());
                if (count.equals(0L)) {
                    //StudentClassType studentClassType = iStudentClassTypeService.getAutoDivideClassType(yearPart,quarterNum,subjectsId,studentId,yearClassId);
                    Grade gradeInfo = this.getNewGrade(yearPart, quarterNum, schoolId, subjectsId, yearClassId, studentId, lessonType);
                    if (gradeInfo != null) {
                        //Long id = this.addData(orderDetailId,schoolId,studentId,gradeInfo.getId(),courseId,subjectsId,yearPart,quarterNum,surplusCourseNum,yearClassId,lessonType,gradeInfo.getCourseTypeId());
                        StudentGrade studentGrade = new StudentGrade();
                        studentGrade.setOrderDetailId(orderDetailId);
                        studentGrade.setSchoolId(schoolId);
                        studentGrade.setStudentId(studentId);
                        studentGrade.setCourseId(courseId);
                        studentGrade.setLessonType(lessonType);
                        studentGrade.setSubjectsId(subjectsId);
                        studentGrade.setYearClassId(yearClassId);
                        studentGrade.setClassTypeIdNew(gradeInfo.getCourseTypeId());
                        studentGrade.setYearPart(yearPart);
                        studentGrade.setQuarterNum(quarterNum);
                        studentGrade.setSurplusCourseNum(surplusCourseNum);
                        studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                        iMqPushService.newStudentSchedule(studentGrade);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
        }
        return true;
    }

    public Grade getNewGrade(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Integer yearClassId, Long studentId, Integer lessonType) {
        GradePositionRequest gradePositionRequest = iStudentClassTypeService.getAutoDivideClassTypeOrScore(yearPart, quarterNum, subjectsId, studentId, yearClassId);
        Grade gradeInfo = null;
        if (gradePositionRequest.getIsHasData().equals(1)) {
            //List<CisPosition> cisPositionList = iCisPositionService.getPositionList(yearPart,quarterNum,schoolId,subjectsId,yearClassId,studentClassType.getClassTypeId(),null,0,1);
            List<Grade> gradeList = iGradeService.getPositionGradeList(yearPart, quarterNum, schoolId, subjectsId, yearClassId, 1, gradePositionRequest.getType(), gradePositionRequest.getScore(), gradePositionRequest.getClassTypeId());
            if (gradeList.size() > 0) {
                gradeInfo = gradeList.get(0);
            }
        }
        return gradeInfo;
    }

    @Override
    @Async("onlineAsync")
    public void autoAllotStudentGrade(Integer yeartPart, Integer quarterNum, Long schoolId, Long subjectsId, Long studentId) {
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

        studentGradeQueryWrapper.eq("year_part", yeartPart);
        studentGradeQueryWrapper.eq("quarter_num", quarterNum);
        studentGradeQueryWrapper.eq(schoolId != null, "school_id", schoolId);
        studentGradeQueryWrapper.eq(subjectsId != null, "subjects_id", schoolId);
        studentGradeQueryWrapper.eq(studentId != null, "student_id", studentId);
        studentGradeQueryWrapper.eq("lesson_type", 1);
        //studentGradeQueryWrapper.eq("grade_id",1867932955985313792L);
        studentGradeQueryWrapper.ne("status", 2);
        studentGradeQueryWrapper.in("reading_status", 0, 1);
        studentGradeQueryWrapper.groupBy("school_id", "student_id", "subjects_id");
        //studentGradeQueryWrapper.eq("'is_last'",1);
        List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);

        for (StudentGrade studentGrade : studentGradeList) {
            iMqPushService.autoAllotStudentGrade(studentGrade);
        }
    }

    @Override
    public Integer useCourseCountByTeacherId(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Long teacherId) {
        return studentGradeMapper.useCourseCountByTeacherId(yearPart, quarterNum, subjectsId, studentId, teacherId);
    }

    /**
     * 查看周内是否已经有排课
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param weekDates
     * @return
     */
    @Override
    public String getWeekDatesPlanGrade(Integer yearPart,
                                        Integer quarterNum,
                                        Long studentId,
                                        String weekDates
    ) {
        return studentGradeMapper.getWeekDatesPlanGrade(yearPart, quarterNum, studentId, weekDates);
    }

    /**
     * 查看周内是否已经有排课（按照课程类型查询）
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param weekDates
     * @return
     */
    @Override
    public String getWeekDatesPlanGradeByLessonType(Integer yearPart,
                                                    Integer quarterNum,
                                                    Long studentId,
                                                    String weekDates,
                                                    Integer lessonType
    ) {
        return studentGradeMapper.getWeekDatesPlanGradeByLessonType(yearPart, quarterNum, studentId, weekDates, lessonType);
    }
}
